from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU

from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex


class SKUSSerializers(serializers.ModelSerializer):
    '''获取当前分类所有商品的序列化器'''
    class Meta:
        model = SKU
        fields = '__all__'


class SKUIndexSerializer(HaystackSerializer):
    """
    SKU索引结果数据序列化器
    """
    object = SKUSSerializers(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')


class SKUHistorySerializer(serializers.Serializer):

    sku_id = serializers.IntegerField(min_value=1)

    # 验证sku_id 商品是否存在
    def validate(self, attrs):
        try:
            SKU.objects.get(id = attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        return attrs

    # 保存商品
    def create(self, validated_data):

        #获取当前用户
        user = self.context['request'].user
        sku_id = validated_data['sku_id']
        # 建立链接对象
        coon  = get_redis_connection('history')
        # 判断当前sku_id是否存在列表中
        # 使用管道,链接对象生成管道对象
        pl = coon.pipeline()

        pl.lrem('history_%s'%user.id, 0, sku_id)
        # 如果不存在写入缓存
        pl.lpush('history_%s'%user.id,sku_id)
        # 控制数量
        pl.ltrim('history_%s'%user.id, 0, 4)
        # 执行管理的内容
        pl.execute()

        return validated_data
